import subprocess

from ..Util.SysUtil import platform


def shell(*cmd, root=False):
    sh = Shell(root=root)
    sh.exec(*cmd)
    return sh.getResultAndClose()


class Shell:
    def __init__(self, root=False):
        keyEnv = 'bash'
        if platform() == 'win32':
            keyEnv = 'adb shell'
        self.sh = subprocess.Popen(keyEnv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                   shell=True)
        if root:
            self.exec('su')
            if 'not found'in self.getResultAndClose():
                print('未取得root权限！')
                exit(-1)

    def exec(self, *cmd):
        newC = ''
        if len(cmd) > 1:
            for i in cmd:
                newC = newC + ' ' + str(i)
        else:
            newC = cmd[0]
        newC = newC + '\n'
        self.sh.stdin.write(newC.encode())

    def getResultAndClose(self):
        out, err = self.sh.communicate()
        if err:
            out = err
        self.exit()
        if out.decode() == '':
            return 0
        return out.decode()

    def exit(self):
        self.sh.stdin.close()
        self.sh.stdout.close()
        self.sh.stderr.close()
        # self.sh.terminate()
        del self
